<?php

class Settings extends Admin_Controller {
    
    function __construct()
    {
        parent::__construct();
        $this->auth->check_access('Admin', true);
        $this->load->model('Settings_model');
        $this->load->model('Messages_model');
        $this->lang->load('settings');
        $this->load->helper('inflector');
    }
    function index(){
        $this->load->helper('form');
        $this->load->library('form_validation');

        $this->form_validation->set_rules('company_name', 'lang:company_name', 'required');
        $this->form_validation->set_rules('theme', 'lang:theme', 'required');
        $this->form_validation->set_rules('email', 'lang:cart_email', 'required|valid_email');

        $this->form_validation->set_rules('country_id', 'lang:country');
        $this->form_validation->set_rules('address1', 'lang:address');
        $this->form_validation->set_rules('address2', 'lang:address');
        $this->form_validation->set_rules('zone_id', 'lang:state');
        $this->form_validation->set_rules('zip', 'lang:zip');
        //$this->form_validation->set_rules('locale', 'lang:locale', 'required');
        $this->form_validation->set_rules('currency_iso', 'lang:currency', 'required');
        $data = $this->Settings_model->get_settings('gocart');
        
        $data['config'] = $data;
        //break out order statuses to an array

        //get installed themes
        $data['themes'] = array();
        if ($handle = opendir(FCPATH.APPPATH.'/themes')) {
            while (false !== ($entry = readdir($handle))) {
                if ($entry != "." && $entry != ".." && is_dir(FCPATH.APPPATH.'/themes/'.$entry)) {
                    $data['themes'][$entry] = $entry;
                }
            }
            closedir($handle);
        }
        asort($data['themes']);
        //get locales
       // $locales = ResourceBundle::getLocales('');
        $data['locales'] = array();
        foreach($locales as $locale)
        {
            $data['locales'][$locale] = locale_get_display_name($locale);
        }
        asort($data['locales']);
        //get ISO 4217 codes
        $data['iso_4217'] = array();
        $iso_4217 =json_decode(json_encode(simplexml_load_file(FCPATH.'ISO_4217.xml')));
        $iso_4217 = $iso_4217->CcyTbl->CcyNtry;
        foreach($iso_4217 as $iso_code)
        {
            if(isset($iso_code->Ccy))
            {
                $data['iso_4217'][$iso_code->Ccy] = $iso_code->Ccy;    
            }
        }
        asort($data['iso_4217']);


        $data['countries_menu'] = $this->Location_model->get_countries_menu();
        if(!empty($data['country_id']))
        {
            $data['zones_menu'] = $this->Location_model->get_zones_menu($data['country_id']);
        }
        else
        {
            $data['zones_menu'] = $this->Location_model->get_zones_menu(array_shift(array_keys($data['countries_menu'])));
        }

        $data['page_title'] = lang('common_gocart_configuration');

        if ($this->form_validation->run() == FALSE)
        {
            $data['error'] = validation_errors();
            $this->view($this->config->item('admin_folder').'/settings', $data);
        }
        else
        {
			
            $this->session->set_flashdata('message', lang('config_updated_message'));

            $save = $this->input->post();
            //fix boolean values
            $save['ssl_support'] = $this->input->post('ssl_support');
            $save['require_login'] = $this->input->post('require_login');
            $save['new_customer_status'] = $this->input->post('new_customer_status');
            $save['allow_os_purchase'] = $this->input->post('allow_os_purchase');
            $save['tax_shipping'] = $this->input->post('tax_shipping');
			
            $this->Settings_model->save_settings('gocart', $save);

            redirect(config_item('admin_folder').'/settings');
        }
        
    }

    function canned_messages()
    {
        $data['canned_messages'] = $this->Messages_model->get_list();
        $data['page_title'] = lang('common_canned_messages');
        $this->view($this->config->item('admin_folder').'/canned_messages', $data);
    }

  
    function canned_message_form($id=false)
    {
        $data['page_title'] = lang('canned_message_form');
        $data['id']         = $id;
        $data['name']       = '';
        $data['subject']    = '';
        $data['content']    = '';
        $data['deletable']  = 1;
        if($id)
        {
            $message = $this->Messages_model->get_message($id);
                        
            $data['name']       = $message['name'];
            $data['subject']    = $message['subject'];
            $data['content']    = $message['content'];
            $data['deletable']  = $message['deletable'];
        }
        
        $this->load->helper('form');
        $this->load->library('form_validation');
        
        $this->form_validation->set_rules('name', 'lang:message_name', 'trim|required|max_length[50]');
        $this->form_validation->set_rules('subject', 'lang:subject', 'trim|required|max_length[100]');
        $this->form_validation->set_rules('content', 'lang:message_content', 'trim|required');
        
        if ($this->form_validation->run() == FALSE)
        {
            $data['errors'] = validation_errors();
            
            $this->view($this->config->item('admin_folder').'/canned_message_form', $data);
        }
        else
        {
            
            $save['id']         = $id;
            $save['name']       = $this->input->post('name');
            $save['subject']    = $this->input->post('subject');
            $save['content']    = $this->input->post('content');
            
            //all created messages are typed to order so admins can send them from the view order page.
            if($data['deletable'])
            {
                $save['type'] = 'order';
            }
            $this->Messages_model->save_message($save);
            
            $this->session->set_flashdata('message', lang('message_saved_message'));
            redirect($this->config->item('admin_folder').'/settings/canned_messages');
        }
    }
    
    function delete_message($id)
    {
        $this->Messages_model->delete_message($id);
        $this->session->set_flashdata('message', lang('message_deleted_message'));
        redirect($this->config->item('admin_folder').'/settings/canned_messages');
    }
	function send_mail_to_customers(){
		set_time_limit(100);
		$post = $this->input->post();
		if(!empty($post)){
			$info_customer_sendemail = $this->info_customer_sendemail($post);
			
			$content = $this->db->where("id",$post["form_mail"])->get("canned_messages")->row();
			
			if(!empty($info_customer_sendemail) and !empty($content)){
				$this->load->helper("email");
				
				$count_email = send_mail_multi($content->subject,$info_customer_sendemail,$this->config->item("header_email").$content->content,$this->config->item("footer_email"),1);
				$this->session->set_flashdata("success","Gửi mail thành công, đã gởi: ".$count_email." mail.");
				redirect("admin/settings/send_mail_to_customers");
			}
		}
		$this->load->model("settings_model");
		$data["type_customer"] = $this->settings_model->get_type_customer();
		$data['canned_messages'] = $this->Messages_model->get_list();
        $data['page_title'] = lang('common_send_mail_to_customers');
        $this->view($this->config->item('admin_folder').'/send_mail_to_customers_form', $data);
	}
	function info_customer_sendemail($post){
		$info_customer_email = array();
		if($post["type_customer"] == 0){
			$info_customer_email = $this->db->select("email,fullname,CONCAT('c') as type,code_active")->get("customers")->result_array();
			$info_customer_email1 = $this->db->select("email,name as fullname,CONCAT('r') as type")->get_where("email_receive_news",array("status"=>'1'))->result_array();
			$info_customer_email = array_merge($info_customer_email,$info_customer_email1);
		}
		elseif($post["type_customer"] > 10){
			$id_type_customer = $post["type_customer"] - 10;
			$info_customer_email = $this->db->select("email,fullname,CONCAT('c') as type,code_active")->get_where('customers',array("email_subscribe"=>1,"group_id"=>$id_type_customer))->result_array();
			$info_customer_email1 = $this->db->select("email,name as fullname,CONCAT('r') as type")->get_where("email_receive_news",array("status"=>'1',"group_id"=>$id_type_customer))->result_array();
			$info_customer_email = array_merge($info_customer_email,$info_customer_email1);			
		}
		elseif($post["type_customer"]==2) 	 $info_customer_email = $this->db->select("email,name as fullname,CONCAT('r') as type,code_active")->get_where("email_receive_news",array("status"=>'1'))->result_array();
		else{
			$email = explode(",",$post["email"]);
			if(!empty($email)) foreach($email as $index => $email){
				$info_customer_email[]["email"] = $email;
			}	
		}
		return $info_customer_email;
	}
	function insert_email(){
	   $admin = $this->session->userdata("admin");
	   $this->load->helper("formatting");
	   if(!empty($_FILES["file"]["name"])){
			$info_data = $this->upload_file($admin);
			
			if($info_data["error"] == 0){
				$info_file= $info_data["data"];
				$this->access_excel($info_file,$admin);
				redirect("admin/settings/insert_email");
			}
		}
		$this->view($this->config->item('admin_folder')."/insert_email");	
	}
	function access_excel($info_file,$admin){
		$this->load->library('excel');
		$objPHPExcel = PHPExcel_IOFactory::load($info_file["full_path"]);
		$sheet = 2;
		$val = array();
		foreach ($objPHPExcel->getWorksheetIterator() as $worksheet){
		   $sheet ++;
		   $worksheetTitle = $worksheet->getTitle();
		   $highestRow = $worksheet->getHighestRow(); // e.g. 10
		   $highestColumn = $worksheet->getHighestColumn(); // e.g 'F'
		   $highestColumnIndex  = PHPExcel_Cell::columnIndexFromString($highestColumn);
		   $info_replace_email  = $this->db->select("email")->get("email_receive_news")->result_array();
		   $info_customer_email = $this->db->select("email")->get("customers")->result_array();
		   $list_email_unset = array();
		   if(!empty($info_replace_email)){
				foreach($info_replace_email as $item){
					$list_email_unset_replace_email[] = $item["email"];	
				}	
			}
		   if(!empty($info_customer_email)){
				foreach($info_customer_email as $item){
					$list_email_unset_customer_email[] = $item["email"];	
				}	
		   }
		   for ($row = 2; $row <= $highestRow; ++ $row) {
			  $email = $worksheet->getCellByColumnAndRow(3,$row)->getValue();
			  $group_id = $worksheet->getCellByColumnAndRow(2,$row)->getValue();
			  $name = $worksheet->getCellByColumnAndRow(1,$row)->getValue();
			  $array_email = explode("@",$email);
			  $md5_email =  md5($email);
			  if(!in_array($email,$list_email_unset_replace_email) and !in_array($email,$list_email_unset_replace_email)){
				  $val_insert[] = array("email"=>$email,"name"=>!empty($name)?$name:$array_email[0],"created"=>time(),"status"=>'1',"code_active"=>$md5_email,"group_id"=>$group_id);
			  }
			  if(in_array($email,$list_email_unset_replace_email)){
				  $val_update_replace_email[] = array("email"=>$email,"group_id"=>$group_id);
			  }
			  if(in_array($email,$list_email_unset_customer_email)){
				  $val_update_customer_email[] = array("email"=>$email,"group_id"=>$group_id);
			  }
		  	}
		 }
		 if(!empty($val_insert))$this->db->insert_batch("email_receive_news",$val_insert);
		 if(!empty($val_update_replace_email))$this->db->update_batch("email_receive_news",$val_update_replace_email,"email");
		 if(!empty($val_update_customer_email))$this->db->update_batch("customers",$val_update_customer_email,"email");
	}
	function upload_file($admin){
		$type = explode(".",$_FILES["file"]["name"]);
		$config['upload_path'] = $_SERVER['DOCUMENT_ROOT'].'/uploads/excel_sendmail/';
		$config["file_name"]   = $admin["username"]."_".date("d-m-Y-H-i-s").".".$type[1];
		$config['allowed_types'] = '*';
		$config['max_size']    = '100000';
		$this->load->library('upload', $config);
		if(!in_array($type[1],array("xls","xlsx"))){
			return array("error"=>1,"data"=>"File không đúng định dạng");
		}else{
			$this->upload->do_upload("file");
			return array("error"=>0,"data"=>$this->upload->data());	
		} 
	}
}